package com.xiaojie.cofnig;

import com.fasterxml.jackson.databind.ser.std.MapSerializer;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * RabbitMQ配置类
 */
@Configuration
public class RabbitMQConfig {
    //交换机名称
    public static final String ITEM_TOPIC_EXCHANGE = "item_topic_exchange";
    //队列名称
    public static final String ITEM_QUEUE = "item_queue";

    public static final String DEMO_ROUTE_KEY = "item.demo";

    public static final String DEAD_LETTER_EXCHANGE = "dead.letter.demo.simple.deadletter.exchange";

    public static final String DEAD_LETTER_QUEUEA_ROUTING_KEY = "dead.letter.queue.routing.key";

    public static final String DEAD_LETTER_QUEUEA_NAME = "dead.letter.queue";

    //声明交换机
    @Bean("itemTopicExchange")
    public Exchange topicExchange(){
        return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build();
    }

    //声明队列
    @Bean("itemQueue")
    public Queue itemQueue(){
        //设置队列中消息的过期时间，单位毫秒，注意如果已存在同名队列则新增参数会保错，将旧队列删除
        Map args = new HashMap();
        args.put("x-message-ttl",10*1000);
        //设置队列的过期时间，如果在时间内未被使用则自动删除队列
        args.put("x-expires",10*1000);
        //配置死信交换器
        args.put("x-dead-letter-exchange",DEAD_LETTER_EXCHANGE);
        //死信队列路由key
        args.put("x-dead-letter-routing-key",DEAD_LETTER_QUEUEA_ROUTING_KEY);
        //配置队列优先级，优先级高的队列中消息优先被消费
        args.put("x-max_priority",10);
        return QueueBuilder.durable(ITEM_QUEUE).withArguments(args).build();
    }



    //配置死信交换器
    @Bean("deadLetterExchange")
    public DirectExchange deadLetterExchange(){
        return new DirectExchange(DEAD_LETTER_EXCHANGE);
    }

    // 声明死信队列A
    @Bean("deadLetterQueueA")
    public Queue deadLetterQueueA(){
        return new Queue(DEAD_LETTER_QUEUEA_NAME);
    }

    //绑定队列和交换机
    @Bean
    public Binding itemQueueExchange(@Qualifier("itemQueue") Queue queue,
                                     @Qualifier("itemTopicExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with("item.#").noargs();
    }


    // 声明死信队列绑定关系
    @Bean
    public Binding deadLetterBindingA(@Qualifier("deadLetterQueueA") Queue queue,
                                      @Qualifier("deadLetterExchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(DEAD_LETTER_QUEUEA_ROUTING_KEY);
    }
}
